package cn.gx.learn.security_boot_jwt_websocket.springsecurity.JWT;

import cn.gx.learn.security_boot_jwt_websocket.base.dal.database.User;
import com.nimbusds.jose.*;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jose.crypto.MACVerifier;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.SignedJWT;

import java.text.ParseException;
import java.util.Date;

public class JWTUtils {
    private static String KEY_WORD="@#hhuu3huh4u7@((hhuhu2jhhh#Bfjjjfk";

    public static String getToken (User user) throws JOSEException {
        JWTClaimsSet.Builder builder=new JWTClaimsSet.Builder();
        builder.subject(user.getUsername());
        builder.claim("user_id",user.getId());
        builder.expirationTime(new Date(System.currentTimeMillis()+3600*1000));
        JWTClaimsSet claimsSet=builder.build();

        JWSSigner signer=new MACSigner(KEY_WORD);
        SignedJWT signedJWT=new SignedJWT(new JWSHeader(JWSAlgorithm.HS256),claimsSet);
        signedJWT.sign(signer);

        return signedJWT.serialize();

    }

    public static User paserToken(String token) throws ParseException, JOSEException {
        SignedJWT signedJWT=SignedJWT.parse(token);
        JWSVerifier verifier=new MACVerifier(KEY_WORD);
        if(!signedJWT.verify(verifier)){
            throw new JOSEException("JWT verification failed");
        }
        JWTClaimsSet claims=signedJWT.getJWTClaimsSet();
        if(claims.getExpirationTime().before(new Date())){
            throw new JOSEException("JWT expired");
        }
        User user=new User(claims.getIntegerClaim("user_id"),claims.getSubject(),null);
        return user;
    }

}
